const util = require('../../utils/util')

Page({
  data: {
    // 当前选中的标签页
    activeTab: 0,
    
    // 拍卖数据
    auctionItem: {
      id: 201,
      name: '限量版球鞋 AJ1',
      currentPrice: 850,
      startPrice: 500,
      timeLeft: '2小时12分',
      progress: 75,
      image: '/static/auction1.jpg' // 替换为实际图片路径
    },
    
    bidPrice: '',
    bidRecords: [
      { user: '张同学', price: 800, time: '2025-03-10 10:20:30' },
      { user: '李同学', price: 820, time: '2025-03-10 10:25:15' },
      { user: '王同学', price: 850, time: '2025-03-10 10:30:40' }
    ],
    
    // 直接购买数据
    product: {
      id: 101,
      name: 'Java编程思想（第4版）',
      price: 35,
      condition: 'likeNew',
      description: '经典Java编程书籍，九成新，有少量笔记',
      image: '/static/images/book.jpg' // 替换为实际图片路径
    },
    
    conditionMap: {
      new: '全新',
      likeNew: '九成新',
      good: '八成新'
    },
    
    addresses: [
      { id: 1, fullAddress: '清华大学紫荆公寓1号楼101室' },
      { id: 2, fullAddress: '清华大学南区学生公寓5号楼203室' }
    ],
    
    orderForm: {
      addressIndex: 0,
      payment: 'alipay',
      remark: ''
    },
    
    // 支付方式选项
    paymentOptions: [
      { value: 'alipay', name: '支付宝' },
      { value: 'wechat', name: '微信支付' },
      { value: 'balance', name: '余额支付' }
    ]
  },

  onLoad() {
    // 检查登录状态
    util.checkLoginStatus();
    
    // 加载拍卖商品
    this.loadAuctionProducts();
    
    // 设置定时器，定期更新剩余时间
    this.timer = setInterval(() => {
      this.updateRemainingTime();
    }, 60000); // 每分钟更新一次
  },
  
  onUnload() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  
  // 加载拍卖商品
  loadAuctionProducts() {
    try {
      // 获取已发布商品
      const publishedProducts = wx.getStorageSync('publishedProducts') || [];
      
      // 筛选拍卖类型的商品
      const auctionProducts = publishedProducts.filter(item => 
        item.tradeType === 'auction' && item.status === '已发布');
      
      if (auctionProducts.length > 0) {
        // 获取第一个拍卖商品
        const auction = auctionProducts[0];
        
        // 计算剩余时间
        const timeLeft = this.calculateRemainingTime(auction.endTimeObj);
        
        // 更新拍卖商品数据
        this.setData({
          'auctionItem': {
            id: auction.id,
            name: auction.name,
            currentPrice: auction.startPrice, // 当前价格初始为起拍价
            startPrice: auction.startPrice,
            timeLeft: timeLeft,
            progress: 0, // 初始进度为0
            image: auction.image
          },
          bidPrice: '' // 确保出价输入框为空
        });
      }
    } catch (e) {
      console.error('加载拍卖商品失败', e);
    }
  },
  
  // 计算剩余时间
  calculateRemainingTime(endTimeObj) {
    if (!endTimeObj) return '未知';
    
    const now = new Date();
    const endTime = new Date(endTimeObj);
    
    // 计算剩余毫秒数
    let diff = endTime - now;
    
    if (diff <= 0) {
      return '已结束';
    }
    
    // 转换为小时和分钟
    const hours = Math.floor(diff / (1000 * 60 * 60));
    diff -= hours * (1000 * 60 * 60);
    
    const minutes = Math.floor(diff / (1000 * 60));
    
    return `${hours}小时${minutes}分`;
  },
  
  // 更新剩余时间
  updateRemainingTime() {
    if (this.data.auctionItem && this.data.auctionItem.id) {
      try {
        // 获取已发布商品
        const publishedProducts = wx.getStorageSync('publishedProducts') || [];
        
        // 找到当前拍卖商品
        const auction = publishedProducts.find(item => item.id === this.data.auctionItem.id);
        
        if (auction && auction.endTimeObj) {
          // 计算剩余时间
          const timeLeft = this.calculateRemainingTime(auction.endTimeObj);
          
          // 更新剩余时间
          this.setData({
            'auctionItem.timeLeft': timeLeft
          });
        }
      } catch (e) {
        console.error('更新剩余时间失败', e);
      }
    }
  },
  
  onShow() {
    // 更新tabBar状态 - 交易选项为索引1
    if (typeof this.getTabBar === 'function') {
      this.getTabBar().setData({
        selected: 1
      });
    }
  },
  
  // 返回首页
  goToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },
  
  // 切换标签页
  switchTab(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      activeTab: index
    });
  },
  
  // 格式化进度条
  formatProgress(percentage) {
    return `已竞价 ${percentage}%`;
  },
  
  // 出价
  placeBid() {
    // 检查出价是否有效
    if (!this.data.bidPrice && this.data.bidPrice !== 0) {
      wx.showToast({
        title: '请输入出价金额',
        icon: 'none'
      });
      return;
    }
    
    const bidPrice = parseFloat(this.data.bidPrice);
    if (isNaN(bidPrice)) {
      wx.showToast({
        title: '请输入有效的金额',
        icon: 'none'
      });
      return;
    }
    
    const currentPrice = this.data.auctionItem.currentPrice;
    
    if (bidPrice <= currentPrice) {
      wx.showToast({
        title: `出价必须高于¥${currentPrice}`,
        icon: 'none'
      });
      return;
    }
    
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    
    const newBidRecords = [{
      user: '我',
      price: bidPrice,
      time: timeString
    }, ...this.data.bidRecords];
    
    let newProgress = this.data.auctionItem.progress;
    if (newProgress < 100) {
      newProgress += 5;
    }
    
    this.setData({
      'bidRecords': newBidRecords,
      'auctionItem.currentPrice': bidPrice,
      'auctionItem.progress': newProgress,
      'bidPrice': '' // 出价成功后清空输入框
    });
    
    wx.showToast({
      title: '出价成功',
      icon: 'success'
    });
  },
  
  // 输入出价
  onBidPriceChange(e) {
    // 获取用户输入的值
    const inputValue = e.detail.value;
    
    // 设置输入值
    this.setData({
      bidPrice: inputValue
    });
    
    // 如果输入不为空，则进行验证
    if (inputValue !== '') {
      const value = parseFloat(inputValue);
      if (!isNaN(value)) {
        const minBid = this.data.auctionItem.currentPrice + 1; // 至少高于当前价格1元
        
        // 如果输入值小于最低出价，则提示用户
        if (value < minBid) {
          wx.showToast({
            title: `最低出价为¥${minBid}`,
            icon: 'none'
          });
        }
      }
    }
  },
  
  // 立即购买
  handleBuy() {
    wx.showToast({
      title: '立即购买',
      icon: 'none'
    });
  },
  
  // 选择地址
  bindAddressChange(e) {
    this.setData({
      'orderForm.addressIndex': e.detail.value
    });
  },
  
  // 选择支付方式
  radioChange(e) {
    this.setData({
      'orderForm.payment': e.detail.value
    });
  },
  
  // 输入备注
  onRemarkInput(e) {
    this.setData({
      'orderForm.remark': e.detail.value
    });
  },
  
  // 添加新地址
  addAddress() {
    wx.showToast({
      title: '添加新地址功能开发中',
      icon: 'none'
    });
  },
  
  // 提交订单
  submitOrder() {
    const selectedAddress = this.data.addresses[this.data.orderForm.addressIndex];
    
    wx.showModal({
      title: '确认提交订单',
      content: `商品: ${this.data.product.name}\n价格: ¥${this.data.product.price}\n地址: ${selectedAddress.fullAddress}`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '提交中...'
          });
          
          // 保存订单记录到本地存储
          this.saveOrderRecord(this.data.product);
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '订单提交成功',
              icon: 'success',
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/index/index'
                  });
                }, 2000);
              }
            });
          }, 1500);
        }
      }
    });
  },
  
  // 保存订单记录
  saveOrderRecord(product) {
    try {
      // 获取现有订单记录
      let purchasedProducts = wx.getStorageSync('purchasedProducts') || [];
      
      // 添加新订单
      const newOrder = {
        id: Date.now(), // 使用时间戳作为唯一ID
        name: product.name,
        price: product.price,
        status: '待收货',
        time: util.formatDate(new Date()),
        image: product.image
      };
      
      // 将新订单添加到列表
      purchasedProducts.unshift(newOrder);
      
      // 存储到本地
      wx.setStorageSync('purchasedProducts', purchasedProducts);
    } catch (e) {
      console.error('保存订单记录失败', e);
    }
  }
}) 